<template>
  <el-dialog :model-value="show" title="添加用户" @close="cancel">
    <el-form :model="form" ref="ruleFormRef" :rules="rules">
      <el-form-item label="账号" prop="username">
        <el-input
          v-model="form.username"
          autocomplete="off"
          placeholder="请输入账号"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="form.nickName"
          autocomplete="off"
          placeholder="请输入姓名"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="form.email"
          autocomplete="off"
          placeholder="请输入邮箱"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          :disabled="id !== 0"
          type="password"
          autocomplete="off"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="form.note"
          autocomplete="off"
          :rows="4"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-radio-group v-model="form.status" class="ml-4">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { addUserAPI, userByIdAPI, editUserAPI } from "./api";
//获取表单DOM元素
const ruleFormRef = ref<FormInstance>();

//获取父组件传递过来的数据
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  id: {
    type: Number,
    default: 0,
  },
});
//监听id有没有发生变化，有就是编辑
watch(
  () => props.id,
  () => {
    if (props.id !== 0) {
      userByIdAPI(props.id).then((res) => {
        if (res.code === 200) {
          //把数据赋值from表单
          Object.assign(form, res.data);
        }
      });
    }
  }
);

//获取父组件传递过来的方法
const emit = defineEmits(["hide"]);
//取消
const cancel = () => {
  //清空表单数据
  ruleFormRef.value?.resetFields();
  form.note = "";
  //关闭对话框
  emit("hide");
};
//表单数据
const form = reactive<IUserListModel>({
  username: "",
  password: "",
  nickName: "",
  status: 0,
  note: "",
  email: "",
});
//判断邮箱是否正确
const validateEmail = (rule: any, value: string, callback: any) => {
  if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
    callback(new Error("请输入正确的邮箱号"));
  } else {
    callback();
  }
};

const rules = reactive({
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  email: [{ validator: validateEmail, trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

//添加用户
const addUser = () => {
  ElMessageBox.confirm("此操作将添加当前用户信息, 是否继续?", "添加用户", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(() => {
      addUserAPI(form).then((res) => {
        if (res.code === 200) {
          //提示添加成功
          ElMessage.success("添加成功");
          //隐藏用户表单
          //刷新数据
          emit("hide", true);
          //清除表单数据
          ruleFormRef.value?.resetFields();
          form.note = "";
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消成功",
      });
    });
};
//编辑用户
const editUser = () => {
  ElMessageBox.confirm("此操作将编辑当前用户信息, 是否继续?", "编辑用户信息", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      editUserAPI(form).then((res) => {
        if (res.code === 200) {
          //提示添加成功
          ElMessage.success("编辑成功");
          //隐藏用户表单
          //刷新数据
          emit("hide", true);
          //清除表单数据
          ruleFormRef.value?.resetFields();
          form.note = "";
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消成功",
      });
    });
};

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (props.id === 0) {
        //添加用户
        addUser();
      } else {
        //编辑用户
        editUser();
      }
    } else {
      ElMessage.error("请输入正确的内容！");
      return false;
    }
  });
};
</script>
<style lang="less" scoped></style>
